package com.bolins.examples.subspringside.mongodb;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;

/**
 * 模糊查询模式
 * 
 * @author liuys
 * 
 */
public abstract class MatchMode implements Serializable {
	private final String name;
	private static final Map<String, MatchMode> INSTANCES = new HashMap<String, MatchMode>();

	protected MatchMode(String name) {
		this.name = name;
	}

	public String toString() {
		return name;
	}

	private Object readResolve() {
		return INSTANCES.get(name);
	}

	/**
	 * 精确匹配(完全匹配)
	 */
	public final static MatchMode EXACT = new MatchMode("exact") {
		private static final long serialVersionUID = 9152502554781561941L;

		@Override
		public String toMatchString(String pattern) {
			if (!pattern.startsWith("^")) {
				pattern = "^" + pattern;
			}

			if (!pattern.endsWith("$")) {
				pattern += "$";
			}

			return pattern;
		}
	};

	/**
	 * 开始精确匹配
	 */
	public final static MatchMode START = new MatchMode("start") {
		private static final long serialVersionUID = 5948526293272556860L;

		@Override
		public String toMatchString(String pattern) {
			if (!pattern.startsWith("^")) {
				pattern = "^" + pattern;
			}
			return pattern;
		}
	};

	/**
	 * 结束精确匹配
	 */
	public final static MatchMode END = new MatchMode("end") {
		private static final long serialVersionUID = -3983024622302926669L;

		@Override
		public String toMatchString(String pattern) {
			if (!pattern.endsWith("$")) {
				pattern += "$";
			}
			return pattern;
		}
	};

	/**
	 * 任意位置匹配
	 */
	public final static MatchMode ANYWHERE = new MatchMode("anywhere") {
		private static final long serialVersionUID = -8510181571749892644L;

		@Override
		public String toMatchString(String pattern) {
			return pattern;
		}
	};

	static {
		INSTANCES.put(EXACT.name, EXACT);
		INSTANCES.put(START.name, START);
		INSTANCES.put(END.name, END);
		INSTANCES.put(ANYWHERE.name, ANYWHERE);
	}

	public abstract String toMatchString(String pattern);

	private static final long serialVersionUID = -902802958560273237L;

}
